


using System;
using System.Security;
using System.Security.Permissions;
using PolePosition.v3.EntityLibrary;


namespace PolePosition.v3.EntityFactory
{
	public sealed partial class CentralOfficeFactory
		: 	Classes.Bases.Factory
	{
	#region " Constructor "
	/// <summary>
	/// Initializes the <c>CentralOfficeFactory</c>.
	/// </summary>
	/// <remarks>No initialization code was present at the time of this documentation.</remarks>
	static CentralOfficeFactory()
	{
		CustomConstructor();
	}
	#endregion

	#region " Internal Save Methods "
    /// <summary>
    /// Persists a <c>CentralOfficeEntity</c> collection to the database, verifying their checksums by default. In the
	/// context of this method, persisting results in either creating, modifying, or deleting the Entities in/from the database,
	/// depending on their state.
    /// </summary>
    /// <param name="saveCollection">Specifies the collection to save.</param>
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
    /// <remarks>No work performed here. Calls the second <see cref="Save(ProjectCommon2.Generics.EntityCollection{Classes.Entities.CentralOfficeEntity}, bool)" />
	/// overload with <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static void Save(ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> saveCollection)
	{
		Save(saveCollection, true);
	}
	
    /// <summary>
    /// Persists a <c>CentralOfficeEntity</c> collection to the database, providing the option to specify whether to verify
	/// their checksums. In the context of this method, persisting results in either creating, modifying, or deleting the 
	/// Entities in/from the database, depending on their state.
    /// </summary>
	///
    /// <param name="saveCollection">Specifies the collection to save.</param>
    /// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data.</param>
	///
	/// <exception cref="ProjectCommon2.Exceptions.FactorySaveException&lt;EntityType&gt;" >
	/// Thrown if the <see cref="Save(Classes.Entities.CentralOfficeEntity)" /> method used to persist individual entities encounters problems
	/// with the entity's Primary Key or checksum. It stores all entities with such problems in an internal collection.
	///</exception>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <remarks>
	/// <para>
	/// Raises an <see cref="OnBeforeSaveCollectionBegin" /> event before starting the save operation. The event argument is an object
	/// of type <see cref="Classes.Bases.BeforeSaveCollectionBeginEventArgs" />, which contains the collection to save and two 
	/// properties that allow event subscribers to let this method know that:
	/// <list type="bullet">
	/// <item>the save operation should be canceled and/or</item>
	/// <item>a SQL transaction is already open (so do not start another one).</item>
	/// </list>
	/// </para>
	/// <para>
	/// If allowed to continue, this method starts a SQL transaction using <see cref="ProjectCommon2.Helpers.TransactionManager.Begin()" />
	/// (if a transaction is not already open), and then it loops through the entity collection and sends every single entity to the
	/// <see cref="Save(Classes.Entities.CentralOfficeEntity)" /> method for saving.
	/// If <c>Save()</c> throws exceptions corresponding to a Primary Key not found, or to a checksum mismatch, then this method saves 
	/// the troubled entity in a <see cref="ProjectCommon2.Exceptions.FactorySaveException&lt;EntityType&gt;" />
	/// object, and attempts to rollback the transaction.
	/// </para>
	/// <para>
	/// Exceptions of any other type are simply rethrown for the system to handle after rolling back the transaction.
	/// If created, the exception object where the troubled entities were saved is always thrown.
	/// </para>
	/// <para>
	/// If no problems were found, then the <see cref="OnBeforeSaveCollectionCommit" /> event is raised before comitting the save
	/// operation to the database. The event argument is an object of type <see cref="Classes.Bases.BeforeSaveCollectionCommitEventArgs" />.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static void Save(ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> saveCollection, bool useCheckSum)
	{

        // raise before event
		bool ThisMethodStartedTheTransaction = false;
		if (OnBeforeSaveCollectionBegin != null)
		{
			Classes.Bases.BeforeSaveCollectionBeginEventArgs args = new Classes.Bases.BeforeSaveCollectionBeginEventArgs();
			args.CancelContinue = false;
			args.BeginTransaction = false;
			args.CollectionToSave = saveCollection;
			args.UseCheckSum = useCheckSum;
			OnBeforeSaveCollectionBegin(null,args);
			if (args.CancelContinue)
			{
				return;
			}
			if (args.BeginTransaction)
			{
				ThisMethodStartedTheTransaction = true;
				ProjectCommon2.Helpers.TransactionManager.Begin();
			}
		}
				
		// loop and save
		ProjectCommon2.Exceptions.FactorySaveException< CentralOfficeEntity> SaveException = null;
		foreach ( CentralOfficeEntity CentralOfficeItem in saveCollection)
		{
			
			try
			{
				if(CentralOfficeItem.IsMarkedToDelete && CentralOfficeItem.IsNew.Value)
					continue;
				
				// pass single entity for an atomic save
				Save(CentralOfficeItem );
			}
			catch (ProjectCommon2.Exceptions.EntityKeyNotFoundException)
			{
				// if single save failed due to KeyNotFound then continue, but persist the entity in exception's inner collection
				if (SaveException == null) 
					{SaveException = new ProjectCommon2.Exceptions.FactorySaveException< CentralOfficeEntity>();}
				if (SaveException.NotFoundEntities == null) 
					{SaveException.NotFoundEntities = new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>();}
                ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> _c = (ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>)SaveException.NotFoundEntities;
				_c.Add(CentralOfficeItem);
			}
			catch (ProjectCommon2.Exceptions.EntityCheckSumConflictException)
			{
				// if single save failed due to CheckSumConflict then continue, but persist the entity in exception's inner collection
				if (SaveException == null) 
					{SaveException = new ProjectCommon2.Exceptions.FactorySaveException< CentralOfficeEntity>();}
				if (SaveException.CheckSumFailedEntities == null) 
					{SaveException.CheckSumFailedEntities = new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>();}
                ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> _c = (ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>)SaveException.NotFoundEntities;
				_c.Add(CentralOfficeItem);
			}
			catch
			{
				ProjectCommon2.Helpers.TransactionManager.Rollback();
				// any other reason for a failure then bubble on up
				throw;
			}
			finally
			{
				// if SaveException was constructed, then throw it
				if (SaveException != null)
				{
					ProjectCommon2.Helpers.TransactionManager.Rollback();
					throw SaveException;
				}
			}
		}
		
		for (int i = saveCollection.Count - 1; i >= 0; i--)
        {
            if (saveCollection[i].IsMarkedToDelete)
                saveCollection.Remove(saveCollection[i]);
        }

        // raise after event
		if (OnBeforeSaveCollectionCommit != null)
		{
			Classes.Bases.BeforeSaveCollectionCommitEventArgs args = new Classes.Bases.BeforeSaveCollectionCommitEventArgs();
			args.CollectionToSave = saveCollection;
			args.UseCheckSum = useCheckSum;
			OnBeforeSaveCollectionCommit(null,args);
		}
		if (ThisMethodStartedTheTransaction) 
		{
			// if this method started the transaction then this method MUST commit it
			ProjectCommon2.Helpers.TransactionManager.Commit();
		}
	
	}
	
    /// <summary>
    /// Persists a single <c>CentralOfficeEntity</c> to the database, verifying its checksum by default. In the
	/// context of this method, persisting results in either creating, modifying, or deleting the Entity in/from the database,
	/// depending on its state.
    /// </summary>
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to save.</param>
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
    /// <remarks>No work performed here. Calls <see cref="Save(Classes.Entities.CentralOfficeEntity, bool)" />
	/// with <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static void Save( CentralOfficeEntity entityToUse)
	{
		Save(entityToUse, true);
	}
	
	/// <summary>
    /// Persists a single <c>CentralOfficeEntity</c> to the database, providing the option to specify whether to verify its
	/// checksum. In the context of this method, persisting results in either creating, modifying, or deleting the Entity 
	/// in/from the database, depending on its state.
    /// </summary>
	///
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to save.</param>
    /// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data.</param>
	///
	/// <exception cref="ProjectCommon2.Exceptions.EntityCheckSumConflictException" >
	/// Thrown if SQL server reports error number 505050, which corresponds to a checksum mismatch between the <c>CentralOfficeEntity</c>
	/// being processed and the one stored in the database (note that the checksum being compared to the database's is 
	/// <c>CentralOfficeEntity</c>'s <see cref="Classes.Entities.CentralOfficeEntity.CheckSumOriginal" />, not a newly calculated one).
	/// The <c>throw</c> is performed using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles
	/// logging and other related activities.
	/// </exception>
	///
	/// <exception cref="ProjectCommon2.Exceptions.EntityKeyNotFoundException" >
	/// Thrown if SQL server reports error number 505060, which corresponds to an attempt to modify a <c>CentralOfficeEntity</c> 
	/// that does not exist in the database (more accurately, the <c>CentralOfficeEntity</c> being processed refers to a database
	/// record whose Primary Key was not found in the database). The <c>throw</c> is performed using 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles logging and other related activities.
	/// </exception>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <remarks>
	/// <para>
	/// Raises an <see cref="OnBeforeSaveEntityBegin" /> event before starting the save operation. The event argument is an
	/// object of type <see cref="Classes.Bases.BeforeSaveEntityBeginEventArgs" />, which contains the <c>CentralOfficeEntity</c>
	/// to be saved and two properties that allow event subscribers to notify this method if:
	/// <list type="bullet">
	/// <item>the save operation should be canceled and/or</item>
	/// <item>a SQL transaction is already open (so do not start another one).</item>
	/// </list>
	/// </para>
	/// <para>
	/// If allowed to continue this method then starts a SQL transaction using <see cref="ProjectCommon2.Helpers.TransactionManager.Begin" />
	/// (if a transaction is not already open) and calls one of the following methods, depending on the state of the given Entity:
	/// <list type="table">
    /// 
    /// <listheader><term>Method used</term><description>Condition</description></listheader>
    /// 
	/// <item><term><see cref="Delete(Classes.Entities.CentralOfficeEntity, bool, bool)" />
	/// <para> </para>
	/// (with <paramref name="obeyIsMarkedToDelete" /> set to <c>true</c>)</term>
	/// <description>If the Entity is marked to be deleted. That is, if
    /// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> is set to <c>true</c>.</description>
    /// </item> 
	///
    /// <item><term><see cref="Update(Classes.Entities.CentralOfficeEntity, bool)" /></term>
	/// <description>Only if the Entity was loaded from the database and has since been modified, but is not marked to be deleted.
	/// That is, only if <see cref="Classes.Entities.CentralOfficeEntity.IsDirty" /> is <c>true</c> but both 
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> and
    /// <see cref="Classes.Entities.CentralOfficeEntity.IsNew" /> are <c>false</c>.</description>
	/// </item>
	///
    /// <item><term><see cref="Insert(Classes.Entities.CentralOfficeEntity)" /></term>
	/// <description>If the Entity contains new data and is not marked to be deleted. 
	/// That is, if <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> is <c>false</c> and 
    /// <see cref="Classes.Entities.CentralOfficeEntity.IsNew" /> is <c>true</c>.</description>
	/// </item>
    /// 
	/// </list>
	/// </para>
	/// <para>
    /// To preserve the integrity and security of the database, the stored procedures used by the first two methods verify that
    /// the Primary Key of the Entity being processed exists in the database and that the value of its
	/// <see cref="Classes.Entities.CentralOfficeEntity.CheckSumOriginal" /> property equals the checksum
    /// of the record being modified. Thus, the operation will fail if the Primary Key does not exist or the checksums do
    /// not match. When any of these events occur, a <see cref="System.Data.SqlClient.SqlException" /> will be thrown, which this
    /// method will catch, retrieve the error code from, and throw exceptions for as specified in the "Exceptions" section above.
	/// </para>
	/// <para>
    /// Any other exceptions will simply be rethrown using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />.
    /// In any case, the method will always attempt to rollback the transaction.
	/// </para>
	/// <para>
	/// Note that the numbers 505050 and 505060 are custom error codes stored in the database's system table.
	/// </para>
	/// <para>
	/// If no problems were found, then the <see cref="OnBeforeSaveEntityCommit" /> event is raised before comitting
	/// the save operation to the database. The event argument is of type <see cref="Classes.Bases.BeforeSaveEntityCommitEventArgs" />,
	/// in which the <c>CentralOfficeEntity</c> to be comitted is passed.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static void Save( CentralOfficeEntity entityToUse, bool useCheckSum)
	{

        // raise before event
		bool ThisMethodStartedTheTransaction = false;
		if (OnBeforeSaveEntityBegin != null)
		{
			Classes.Bases.BeforeSaveEntityBeginEventArgs args = new Classes.Bases.BeforeSaveEntityBeginEventArgs();
			args.CancelContinue = false;
			args.BeginTransaction = false;
			args.EntityToSave = entityToUse;
			args.UseCheckSum = useCheckSum;
			OnBeforeSaveEntityBegin(null,args);
			if (args.CancelContinue)
			{
				return;
			}
			if (args.BeginTransaction)
			{
				ThisMethodStartedTheTransaction = true;
				ProjectCommon2.Helpers.TransactionManager.Begin();
			}
		}
		
		try
		{
		
            if ((bool)entityToUse.IsMarkedToDelete && !entityToUse.IsNew.Value)
			{
				Delete(entityToUse, true, useCheckSum);
            }
            else if (!(bool)entityToUse.IsMarkedToDelete & !(bool)entityToUse.IsNew & (bool)entityToUse.IsDirty)
			{
				Update(entityToUse, useCheckSum);
            }
            else if (!(bool)entityToUse.IsMarkedToDelete & (bool)entityToUse.IsNew)
			{
				Insert(entityToUse);
			}
	
			// nothing possible (should be exception? probably not.)

		}
		catch (System.Data.SqlClient.SqlException ex)
		{
			ProjectCommon2.Helpers.TransactionManager.Rollback();
			switch (ex.Number)
			{
				case 505050: 
					ProjectCommon2.Helpers.ExceptionHelper.Throw(new ProjectCommon2.Exceptions.EntityCheckSumConflictException(ex));
					break;
				case 505060: 
					ProjectCommon2.Helpers.ExceptionHelper.Throw(new ProjectCommon2.Exceptions.EntityKeyNotFoundException(ex));
					break;
				default:
					ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
					break;
			}
		}
		catch(Exception ex)
		{
			ProjectCommon2.Helpers.TransactionManager.Rollback();
			// throw whatever it is
			ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
		}
		
        // raise after event
		if (OnBeforeSaveEntityCommit != null)
		{
			Classes.Bases.BeforeSaveEntityCommitEventArgs args = new Classes.Bases.BeforeSaveEntityCommitEventArgs();
			args.EntityToSave = entityToUse;
			args.UseCheckSum = useCheckSum;
			OnBeforeSaveEntityCommit(null,args);
		}
		if (ThisMethodStartedTheTransaction) 
		{
			// if this method started the transaction then this method MUST commit it
			ProjectCommon2.Helpers.TransactionManager.Commit();
		}
			
	}
	#endregion
	
	#region " Internal Get Entity Methods "

    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> from the database, using the supplied Primary Key as the only parameter to the
	/// query. Verifies the checksum by default.
    /// </summary>
    /// <param name="centralOfficeId">Specifies the Primary Key of the <c>CentralOfficeEntity</c>
	/// to retrieve.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
    /// <returns>New instance of <see cref="Classes.Entities.CentralOfficeEntity" />, loaded with the values from
	/// a database record. However, <c>null</c> will be returned if <paramref name="centralOfficeId" />
	/// is <c>null</c>, or if an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>No work performed here. Calls <see cref="GetEntity(int?, bool)" />
	/// with <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static  CentralOfficeEntity GetEntity(int? centralOfficeId)
	{
		return GetEntity(centralOfficeId, true);
	}
	
    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> from the database, using the supplied Primary Key as the only parameter to the
	/// query. Provides the option to disable checksum verification.
    /// </summary>
    /// <param name="centralOfficeId">Specifies the Primary Key of the <c>CentralOfficeEntity</c>
	/// to retrieve.</param>
	///
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data before retrieving it.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <returns>New instance of <see cref="Classes.Entities.CentralOfficeEntity" />, loaded with the values from
	/// a database record. However, <c>null</c> will be returned if <paramref name="centralOfficeId" />
	/// is <c>null</c>, or if an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>Creates a new <c>CentralOfficeEntity</c> object using the parameterless <c>CentralOfficeEntity()</c>
	/// constructor (see the list of <see cref="Classes.Entities.CentralOfficeEntity()" />s) and assigns it the Primary Key specified in
	/// <paramref name="centralOfficeId" />. Then it calls 
	/// <see cref="GetEntity(Classes.Entities.CentralOfficeEntity, bool)" />, with <paramref name="entityToUse" /> set to the 
	/// <c>CentralOfficeEntity</c> just created, and <paramref name="useCheckSum" /> set to the value specified for this method.
	/// </para>
	/// <para>If <paramref name="centralOfficeId" /> is <c>null</c>,
	/// this method will end and return a <c>null</c> value.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static  CentralOfficeEntity GetEntity(int? centralOfficeId, bool useCheckSum)
	{
		//centralOfficeId == null return null
		if (centralOfficeId == null){return null;}
		CentralOfficeEntity entityToUse;
		entityToUse = new CentralOfficeEntity();
		entityToUse.CentralOfficeId = centralOfficeId;
		return GetEntity(entityToUse, useCheckSum);
	}
	
    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> from the database, using the column properties of the
	/// supplied Entity as parameters to the query. Verifies the checksum by default.
    /// </summary>
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to use as a filter for the query results.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <returns>New instance of <see cref="Classes.Entities.CentralOfficeEntity" />, loaded with the values from
	/// a database record. However, <c>null</c> will be returned if <paramref name="entityToUse" /> is <c>null</c>, or if 
	/// an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>No work performed here. Calls <see cref="GetEntity(Classes.Entities.CentralOfficeEntity, bool)" />
	/// with <paramref name="entityToUse" /> set to the passed-in <c>CentralOfficeEntity</c> and
	/// <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static  CentralOfficeEntity GetEntity( CentralOfficeEntity entityToUse)
	{
		return GetEntity(entityToUse, true);
	}

    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> from the database, using the column properties of the
	/// supplied Entity as parameters to the query. Provides the option to disable checksum verification.
    /// </summary>
	///
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to use as a filter for the query results.</param>
	///
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data before 
	/// retrieving it.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	/// 
    /// <exception cref="ProjectCommon2.Exceptions.MissingDataTableException">
	/// Thrown if there are no tables in the <c>DataSet</c> resulting from executing the query. Thrown 
	/// using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles
	/// logging and other related activities.
	/// </exception>
    ///
	/// <returns>New instance of <see cref="Classes.Entities.CentralOfficeEntity" />, loaded with the values from
	/// a database record. However, <c>null</c> will be returned if <paramref name="entityToUse" /> is <c>null</c>, or if 
	/// an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>This method works by sending parameters to a stored procedure in the database. First, a 
	/// <see cref="System.Data.SqlClient.SqlCommand" /> is built, specifying "up_CentralOffice_Select_Top1"
	/// as the name of the stored procedure to execute. The parameters sent to the procedure are simply
	/// the values of the column properties of the <c>CentralOfficeEntity</c> passed in <paramref name="entityToUse" />. In this
	/// way, the Entity determines which record, if any, will be selected from the database (the one containing the same values as
	/// the Entity). The values are extracted from the Entity and inserted into the <c>SqlCommand</c> by the 
	/// <see cref="FillCommandParameters(System.Data.SqlClient.SqlCommand, Classes.Entities.CentralOfficeEntity)" /> method.
	/// </para>
	/// 
	/// <para>The method then raises an <see cref="OnBeforeGetEntity" /> event before executing the <c>SqlCommand</c>.
	/// The event argument is an object of type <see cref="Classes.Bases.BeforeGetEntityEventArgs" />, which allows this method
	/// to pass the <c>CentralOfficeEntity</c> to filter with, the <c>SqlCommand</c>, and the value in <paramref name="useCheckSum" />
	/// to any object subscribed to the event.
	/// </para>
	///
	/// <para>The <c>SqlCommand</c> is then executed using <see cref="ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet" />, and if
	/// the resulting <see cref="System.Data.DataSet" /> is empty, an exception is thrown as specified in the "Exceptions" section
	/// above. If not, the values of the first row (row 0) in the topmost table (table 0) are sent to the
	/// <see cref="Classes.Entities.CentralOfficeEntity(System.Data.DataRow, bool)" /> constructor to create a new
	/// <c>CentralOfficeEntity</c>, provided that a row exists in the table.
	/// </para>
	///
	/// <para>Before the newly created <c>CentralOfficeEntity</c> is returned as the result, an <see cref="OnAfterGetEntity" /> event
	/// is raised, sending the following items in the <see cref="Classes.Bases.AfterGetEntityEventArgs" /> object:
	/// <list type="bullet">
	/// <item>The <c>CentralOfficeEntity</c> used to filter the results,</item>
	/// <item>the checksum verification setting,</item>
	/// <item>the <c>SqlCommand</c> that was executed, </item>
	/// <item>the results <c>DataSet</c>,</item>
	/// <item>and the <c>CentralOfficeEntity</c> to be returned.</item>
	/// </list>
	/// </para>
	/// 
	/// <para>If this process fails at any point, any exceptions thrown will be handled by the
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> method.
	/// </para>
	/// <para><b>Note</b>: if the Entity passed in <paramref name="entityToUse" /> is empty (contains no values for any of its
	/// column properties), the stored procedure will return all the records in the CentralOffice table, from which this method will
	/// pick only the topmost one, as specified above.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static  CentralOfficeEntity GetEntity( CentralOfficeEntity entityToUse, bool useCheckSum)
	{		
			//If the entity is null return null
			if (entityToUse==null){return null;}
			try
			{
				
				// build command
				System.Data.SqlClient.SqlCommand SqlCmd;
				SqlCmd = new System.Data.SqlClient.SqlCommand();
				SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
				SqlCmd.CommandText = "up_CentralOffice_Select_Top1";
				

				// parameters
				FillCommandParameters(SqlCmd, entityToUse);

                // raise before event
				if (OnBeforeGetEntity != null)
				{
					Classes.Bases.BeforeGetEntityEventArgs args = new Classes.Bases.BeforeGetEntityEventArgs();
					args.EntityToFilterWith = entityToUse;
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					OnBeforeGetEntity(null,args);
				}

				// execute
				System.Data.DataSet ds;
				ds = ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet(SqlCmd);
				
				System.Data.DataTable dt;
				if (ds.Tables.Count == 0)
				{
					ProjectCommon2.Exceptions.MissingDataTableException ex = new ProjectCommon2.Exceptions.MissingDataTableException("Results expect at least one member table.");
					ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}
				dt = ds.Tables[0];

				// fill collection
				 CentralOfficeEntity _e = null;
				if (dt.Rows.Count != 0)
				{
					// attempt to fill only if there is anything to put in it
					_e = new  CentralOfficeEntity(dt.Rows[0], useCheckSum);
				}

                // raise after event
				if (OnAfterGetEntity != null)
				{
					Classes.Bases.AfterGetEntityEventArgs args = new Classes.Bases.AfterGetEntityEventArgs();
					args.EntityToFilterWith = entityToUse;
					args.DataSetFromDataBase = ds;
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					args.EntityToReturn = _e;
					OnAfterGetEntity(null,args);
				}
				
				return _e;
				
			}
			catch (Exception ex)
			{
				ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
			}
			return null;
		
	}

	#endregion 
	
	#region " Internal Get Collection Methods "

    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> collection from the database, sending no parameters to the 
	/// query. Currently this returns all CentralOffice records in the database. Verifies checksums by default.
    /// </summary>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
    /// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, <c>null</c> will be returned if 
	/// an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>No work performed here. Calls <see cref="GetCollection(bool)" />
	/// with <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </para>
	/// <para>Note that at the time of this document, this method returns every existent <c>CentralOfficeEntity</c>,
	/// since the stored procedure that executes the query is currently configured to return all CentralOffice records found in
	/// the database if it is not provided with parameters to filter the results with.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection()
	{
		return GetCollection(true);
	}

    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> collection from the database, sending no parameters to the query. Currently 
	/// this returns all CentralOffice records in the database. Provides the option to disable checksums verification.
    /// </summary>
	///
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data before 
	/// retrieving it.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
    /// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, <c>null</c> will be returned if 
	/// an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>Creates a new, empty <c>CentralOfficeEntity</c> object using the parameterless <c>CentralOfficeEntity()</c>
	/// constructor (see the list of <see cref="Classes.Entities.CentralOfficeEntity()" />s). Then it calls 
	/// <see cref="GetCollection(Classes.Entities.CentralOfficeEntity, bool)" />, with <paramref name="entityToUse" /> set to the 
	/// <c>CentralOfficeEntity</c> just created, and <paramref name="useCheckSum" /> set to the value specified for this method.
	/// </para>
	/// <para>Note that at the time of this document, this method returns every existent <c>CentralOfficeEntity</c>,
	/// since the stored procedure that executes the query is currently configured to return all CentralOffice records found in
	/// the database if it is not provided with parameters to filter the results with.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection(bool useCheckSum)
	{
		 CentralOfficeEntity _e;
		_e = new  CentralOfficeEntity();
		return GetCollection(_e, useCheckSum);
	}
	
    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> collection composed of all the Entities in the database that match any one of
	/// the Entities in the supplied filtering collection. Use this as a shortcut for having to call the 
	/// <see cref="GetCollection(Classes.Entities.CentralOfficeEntity, bool)" /> overload multiple times with a different
	/// filtering Entity every time. Verifies checksums by default.
    /// </summary>
	///
	/// <param name="entityCollection">Specifies the <c>CentralOfficeEntity</c> collection to use in filtering
	/// the query results.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
    /// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, if <paramref name="entityToUse" /> is 
	/// <c>null</c>, an empty collection will be returned, or <c>null</c> if an exception is thrown and the method used to
	/// handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>No work performed here. Calls
	/// <see cref="GetCollection(ProjectCommon2.Generics.EntityCollection&lt;Classes.Entities.CentralOfficeEntity&gt;, bool)" />
	/// with <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection(ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> entityCollection)
	{
		return GetCollection(entityCollection, true);
	}

    /// <summary>
    /// Retrieves a <c>CentralOfficeEntity</c> collection composed of all the Entities in the database that match any one of
	/// the Entities in the supplied filtering collection. Use this as a shortcut for having to call the 
	/// <see cref="GetCollection(Classes.Entities.CentralOfficeEntity, bool)" /> overload multiple times with a different
	/// filtering Entity every time. Provides the option to disable checksum verification.
    /// </summary>
	///
	/// <param name="entityCollection">Specifies the <c>CentralOfficeEntity</c> collection to use in filtering
	/// the query results.</param>
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data before retrieving it.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
    /// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, if <paramref name="entityToUse" /> is 
	/// <c>null</c>, an empty collection will be returned, or <c>null</c> if an exception is thrown and the method used to 
	/// handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>Sends every entity contained in the passed-in <c>CentralOfficeEntity</c> collection separately to  
	/// <see cref="GetCollection(Classes.Entities.CentralOfficeEntity, bool)" />, with <paramref name="useCheckSum"/> set to
	/// the value specified for this method.
	/// </para>
	/// <para>It merges the collections resulting from every one of these calls into a new <c>CentralOfficeEntity</c> collection,
	/// using its <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;.Merge" /> method with 
	/// <paramref name="allowDuplicates"/> set to <c>false</c>, and then returns the new collection.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection(ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> entityCollection, bool useCheckSum)
	{
		ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> _c;
		_c = new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>();
		
		//make sure _c != null
		if (entityCollection != null){
			// merge multiple results to a single collection
			foreach ( CentralOfficeEntity _e in entityCollection)
			{
				_c.Merge(GetCollection(_e, useCheckSum), false);
			}
		}
		return _c;
	}
	
    /// <summary>
	/// Retrieves a <c>CentralOfficeEntity</c> collection composed of all the Entities in the database that match the 
	/// supplied filtering Entity. Verifies checksums by default.
    /// </summary>
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to use as a filter for the query results.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, if <paramref name="entityToUse" /> is 
	/// <c>null</c>, an empty collection will be returned, or <c>null</c> if an exception is thrown and the method used to
	/// handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>No work performed here. Calls <see cref="GetCollection(Classes.Entities.CentralOfficeEntity, bool)" />
	/// with <paramref name="entityToUse" /> set to the passed-in <c>CentralOfficeEntity</c> and
	/// <paramref name="useCheckSum"/> set to <c>true</c>.
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection( CentralOfficeEntity entityToUse)
	{
		return GetCollection(entityToUse, true);
	}
	
    /// <summary>
	/// Retrieves a <c>CentralOfficeEntity</c> collection composed of all the Entities in the database that match the 
	/// supplied filtering Entity. Provides the option to disable checksum verification.
    /// </summary>
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to use as a filter for the query results.</param>
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data before retrieving it.</param>
	///
	/// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
	///
	/// <exception cref="ProjectCommon2.Exceptions.MissingDataTableException">
	/// Thrown if there are no tables in the <c>DataSet</c> resulting from executing the query. Thrown 
	/// using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles
	/// logging and other related activities.
	/// </exception>
	///
	///
	/// <returns>New instance of <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;" />,
	/// where each Entity is loaded with the values from a database record. However, if <paramref name="entityToUse" /> is 
	/// <c>null</c>, or the results <c>DataSet</c> is empty, an empty collection will be returned. <c>Null</c> will be 
	/// returned if an exception is thrown and the method used to handle exceptions does not rethrow the exception (see how 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> works).
	/// </returns>
	///
	/// <remarks>
	/// <para>This method works by sending parameters to a stored procedure in the database. First, a 
	/// <see cref="System.Data.SqlClient.SqlCommand" /> is built, specifying "up_CentralOffice_Select"
	/// as the name of the stored procedure to execute. The parameters sent to the procedure are simply
	/// the values of the column properties of the <c>CentralOfficeEntity</c> passed in <paramref name="entityToUse" />. In this
	/// way, the Entity determines which records, if any, will be selected from the database (those containing the same values as
	/// the Entity). The values are extracted from the Entity and inserted into the <c>SqlCommand</c> by the 
	/// <see cref="FillCommandParameters(System.Data.SqlClient.SqlCommand, Classes.Entities.CentralOfficeEntity)" /> method.
	/// </para>
	/// 
	/// <para>The method then raises an <see cref="OnBeforeGetEntityCollection" /> event before executing the <c>SqlCommand</c>.
	/// The event argument is an object of type <see cref="Classes.Bases.BeforeGetEntityCollectionEventArgs" />, which allows this 
	/// method to pass the <c>CentralOfficeEntity</c> to filter with, the <c>SqlCommand</c>, and the value in 
	/// <paramref name="useCheckSum" /> to any object subscribed to the event.
	/// </para>
	///
	/// <para>The <c>SqlCommand</c> is then executed using <see cref="ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet" />, and if
	/// the resulting <see cref="System.Data.DataSet" /> is empty, an exception is thrown as specified in the "Exceptions" section
	/// above. If not, the topmost table (table 0) in the <see cref="System.Data.DataSet" /> is chosen, and if it is not empty, 
	/// sent to the <see cref="ProjectCommon2.Generics.EntityCollection&lt;EntityType&gt;(System.Data.DataTable, bool)" />
	/// constructor to create a new <c>CentralOfficeEntity</c> collection (with <paramref name="useCheckSum" /> set to the value
	/// specified for this method). An empty collection is created when the results table is empty.
	/// </para>
	///
	/// <para>Before the newly created collection is returned as the result, an <see cref="OnAfterGetEntityCollection" /> event
	/// is raised, sending the following items in the <see cref="Classes.Bases.AfterGetEntityCollectionEventArgs" /> object:
	/// <list type="bullet">
	/// <item>The <c>CentralOfficeEntity</c> used to filter the results,</item>
	/// <item>the checksum verification setting,</item>
	/// <item>the <c>SqlCommand</c> that was executed, </item>
	/// <item>the results <c>DataSet</c>,</item>
	/// <item>and the <c>CentralOfficeEntity</c> collection to be returned.</item>
	/// </list>
	/// </para>
	/// 
	/// <para>If this process fails at any point, any exceptions thrown will be handled by
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" /> and this method will return a <c>null</c> value.
	/// </para>
	///
	/// <para><b>Note</b>: if the entity passed in <paramref name="entityToUse" /> is empty (contains no values for any of its
	/// column properties), the stored procedure in its current form will return all records found in the CentralOffice table.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	public static ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> GetCollection( CentralOfficeEntity entityToUse, bool useCheckSum)
	{
			if (entityToUse==null){return new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>();}
			
			try
			{
				// build command
				System.Data.SqlClient.SqlCommand SqlCmd;
				SqlCmd = new System.Data.SqlClient.SqlCommand();
				SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
				SqlCmd.CommandText = "up_CentralOffice_Select";
				

				// parameters
				FillCommandParameters(SqlCmd, entityToUse);

                // raise before event
				if (OnBeforeGetEntityCollection != null)
				{
					Classes.Bases.BeforeGetEntityCollectionEventArgs args = new Classes.Bases.BeforeGetEntityCollectionEventArgs();
					args.EntityToFilterWith = entityToUse;
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					OnBeforeGetEntityCollection(null,args);
				}

				// execute
				System.Data.DataSet ds;
				ds = ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet(SqlCmd);
				
				System.Data.DataTable dt;
				if (ds.Tables.Count == 0)
				{
					ProjectCommon2.Exceptions.MissingDataTableException ex = new ProjectCommon2.Exceptions.MissingDataTableException("Results expect at least one member table.");
					ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}
				dt = ds.Tables[0];

				// fill collection
				ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity> _c = null;
				if (dt.Rows.Count != 0)
				{
					// attempt to fill only if there is anything to put in it
					_c = new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>(dt,useCheckSum);
				}
				else
				{
					_c = new ProjectCommon2.Generics.EntityCollection< CentralOfficeEntity>();
				}

                // raise after event
				if (OnAfterGetEntityCollection != null)
				{
					Classes.Bases.AfterGetEntityCollectionEventArgs args = new Classes.Bases.AfterGetEntityCollectionEventArgs();
					args.EntityToFilterWith = entityToUse;
					args.DataSetFromDataBase = ds;
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					args.CollectionToReturn = _c;
					OnAfterGetEntityCollection(null,args);
				}
				
				return _c;
				
			}
			catch (Exception ex)
			{
				ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
			}
			return null;
	}

	#endregion 

	#region " Private Persist Methods "

    /// <summary>
	/// Creates a new record in the database, using the column properties of the given Entity as parameters to the INSERT command.
	/// </summary>
    /// 
    /// <param name="entityToInsert">Specifies the <c>CentralOfficeEntity</c> whose values are to be inserted.</param>
    /// 
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
    /// 
	/// <exception cref="ProjectCommon2.Exceptions.MissingDataTableException">
	/// Thrown if there are no tables in the <c>DataSet</c> resulting from executing the query. Thrown 
	/// using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles
	/// logging and other related activities.
	/// </exception>
    /// <exception cref="ProjectCommon2.Exceptions.BaseException">
	/// Thrown if there are no rows in the topmost table in the <c>DataSet</c>, with the following error message: 
	/// "Failed on CentralOfficeFactory.Insert(): No Data Rows in Data Table."<para> </para>
	/// The <c>throw</c> is performed using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />,
	/// which handles logging and other related activities.
	/// </exception>
	/// 
    /// 
    /// <remarks>
	/// <para>This method works by sending parameters to a stored procedure in the database, which in turn executes an INSERT
	/// command with the same parameters. First, a <see cref="System.Data.SqlClient.SqlCommand" /> is built, specifying 
	/// "up_CentralOffice_Insert" as the name of the stored procedure to execute. The parameters sent
	/// to the procedure are simply the values of the column properties of the <c>CentralOfficeEntity</c> passed in 
	/// <paramref name="entityToInsert" />. The values are extracted from the Entity and inserted into the <c>SqlCommand</c> by the 
	/// <see cref="FillCommandParameters(System.Data.SqlClient.SqlCommand, Classes.Entities.CentralOfficeEntity)" /> method. Note that
	/// the Entity's <see cref="Classes.Entities.CentralOfficeEntity.EnableDefaults" /> property is set to <c>true</c> before
	/// calling that method.
	/// </para>
	/// <para>The method then raises an <see cref="OnBeforeEntityInsert" /> event before executing the <c>SqlCommand</c>.
	/// The event argument is an object of type <see cref="Classes.Bases.BeforeEntityInsertEventArgs" />, which allows this method
	/// to pass the <c>CentralOfficeEntity</c> to be inserted and the <c>SqlCommand</c> to be executed to any object subscribed
	/// to the event.
	/// </para>
	///
	/// 
	///
	/// <para>The <c>SqlCommand</c> is then executed using <see cref="ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet" />. The
	/// "up_CentralOffice_Insert" procedure is configured to SELECT the record right after inserting it,
	/// so it should return a <see cref="System.Data.DataSet" /> containing it. If the resulting <see cref="System.Data.DataSet" />
	/// contains no tables, an exception is thrown as specified in the "Exceptions" section above.
	/// </para>
	///
	/// <para>After this, an <see cref="OnAfterEntityInsert" /> event is raised, sending the following items in the
	/// <see cref="Classes.Bases.AfterEntityInsertEventArgs" /> object:
	/// <list type="bullet">
	/// <item>The given <c>CentralOfficeEntity</c> to insert,</item>
	/// <item>the <c>SqlCommand</c> that was executed, and</item>
	/// <item>the results <c>DataSet</c>.</item>
	/// </list>
	/// </para>
	/// 
	/// <para>This method then proceeds to reload the passed-in Entity with the values from the returned <c>DataSet</c>. 
	/// If the topmost table is empty, a system exception is thrown as specified in the "Exceptions" section above. If not, row 0 (zero)
	/// is chosen and sent to the Entity's
	/// <see cref="Classes.Entities.CentralOfficeEntity.LoadFromDataRow(System.Data.DataRow, bool)" /> method, with 
	/// <paramref name="useCheckSum" /> set to <c>false</c>. Also, its 
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> property is set to <c>false</c>.
	/// </para>
	///
	/// 
	/// <para><b>Note</b>: there is a version of this method where a checksum is stored previous to inserting the Entity and at this 
	/// point compares it with the checksum from the reloaded Entity. This is done to correct discrepancies that may arise even though
	/// <see cref="Classes.Entities.CentralOfficeEntity.EnableDefaults" /> is set to <c>true</c> before executing the INSERT command.
	/// That method was generated at compile time only for those Entities that are supposed to deal with tables that contain checksum
	/// fields.</para>
	/// 
	/// <para>
	/// Any other exceptions generated at any point in this process are handled by
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	private static void Insert(CentralOfficeEntity entityToInsert)
	{
			try
			{
		
				// build command
				System.Data.SqlClient.SqlCommand SqlCmd;
				SqlCmd = new System.Data.SqlClient.SqlCommand();
				SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
				SqlCmd.CommandText = "up_CentralOffice_Insert";
				
				// parameters
				entityToInsert.EnableDefaults = true;
				FillCommandParameters(SqlCmd, entityToInsert);
				
                // raise before event
				if (OnBeforeEntityInsert != null) 
				{
	                Classes.Bases.BeforeEntityInsertEventArgs args = new Classes.Bases.BeforeEntityInsertEventArgs();
					args.EntityToInsert = entityToInsert;
					args.SqlCommandToExecute = SqlCmd;
					OnBeforeEntityInsert(null,args);
				}
				

				// execute
                SqlCmd.Transaction = ProjectCommon2.Helpers.TransactionManager.Transaction;
				System.Data.DataSet ds;
				ds = ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet(SqlCmd);
				
				System.Data.DataTable dt;
				if (ds.Tables.Count == 0)
				{
					ProjectCommon2.Exceptions.MissingDataTableException ex = new ProjectCommon2.Exceptions.MissingDataTableException("Results expect at least one member table.");
					ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}
				dt = ds.Tables[0];

                // raise after event
				if (OnAfterEntityInsert != null) 
				{
	                Classes.Bases.AfterEntityInsertEventArgs args = new Classes.Bases.AfterEntityInsertEventArgs();
					args.EntityToInsert = entityToInsert;
					args.SqlCommandToExecute = SqlCmd;
					args.DataSetFromDataBase = ds;
					OnAfterEntityInsert(null,args);
				}

				// reload
				if (dt.Rows.Count == 0)
				{
					ProjectCommon2.Exceptions.BaseException ex;
					ex = new ProjectCommon2.Exceptions.BaseException(string.Format("Failed on CentralOfficeFactory.Insert(): No Data Rows in Data Table."));
                    ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}

                entityToInsert.LoadFromDataRow(dt.Rows[0], false);
				entityToInsert.IsMarkedToDelete = false;

				
			}
			catch (Exception ex)
			{
				ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
			}
	}

    /// <summary>
	/// Modifies an existing database record, using the column properties of the given Entity as parameters to the UPDATE command.
	/// </summary>
    /// 
    /// <param name="entityToUpdate">Specifies the <c>CentralOfficeEntity</c> whose corresponding record is to be modified.</param>
    /// 
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission> 
    /// 
    /// <remarks>
	/// <para>
	/// No work performed here. Calls <see cref="Update(Classes.Entities.CentralOfficeEntity, bool)" /> with
	/// <paramref name="useCheckSum" /> set to <c>true</c>.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	private static void Update(CentralOfficeEntity entityToUpdate)
	{
		Update(entityToUpdate, true);
	}

    /// <summary>
	/// Modifies an existing database record, using the column properties of the given Entity as parameters to the UPDATE command.
	/// Provides the option to disable checksum verification.
	/// </summary>
    /// 
    /// <param name="entityToUpdate">Specifies the <c>CentralOfficeEntity</c> whose corresponding record is to be modified.</param>
	/// <param name="useCheckSum">Allows the use of a checksum to verify the updated data.</param>
    /// 
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
    /// 
	/// <exception cref="ProjectCommon2.Exceptions.MissingDataTableException">
	/// Thrown if there are no tables in the <c>DataSet</c> resulting from executing the query. Thrown 
	/// using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which handles
	/// logging and other related activities.
	/// </exception>
    /// <exception cref="ProjectCommon2.Exceptions.BaseException">
	/// Thrown if there are no rows in the topmost table in the <c>DataSet</c>, with the following error message: 
	/// "Failed on CentralOfficeFactory.Update(): No Data Rows in Data Table."<para> </para>
	/// The <c>throw</c> is performed using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />,
	/// which handles logging and other related activities.
	/// </exception>
	/// 
    /// 
    /// <remarks>
	/// 
	///	<para>This method works by sending parameters to a stored procedure in the database, which in turn executes an UPDATE
	/// command with the same parameters. First, a <see cref="System.Data.SqlClient.SqlCommand" /> is built, specifying 
	/// "up_CentralOffice_Update" as the name of the stored procedure to execute. The parameters sent
	/// to the procedure are simply the values of the column properties of the <c>CentralOfficeEntity</c> passed in 
	/// <paramref name="entityToUpdate" />. The values are extracted from the Entity and inserted into the <c>SqlCommand</c> by the 
	/// <see cref="FillCommandParameters(System.Data.SqlClient.SqlCommand, Classes.Entities.CentralOfficeEntity)" /> method. Note that
	/// the Entity's <see cref="Classes.Entities.CentralOfficeEntity.EnableDefaults" /> property is set to <c>true</c> before
	/// calling that method.
	/// </para>
	/// 
	/// 
	/// 
	/// <para>The method then raises an <see cref="OnBeforeEntityUpdate" /> event before executing the <c>SqlCommand</c>.
	/// The event argument is an object of type <see cref="Classes.Bases.BeforeEntityUpdateEventArgs" />, which allows this method
	/// to pass the <c>CentralOfficeEntity</c> to be updated, the <c>SqlCommand</c> to be executed, and the value passed in 
	/// <paramref name="useCheckSum" /> to any object subscribed to the event.
	/// </para>
	///
	/// 
	///
	/// <para>The <c>SqlCommand</c> is then executed using <see cref="ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet" />. The
	/// stored procedure is configured to SELECT the record right after updating it, so it should return a
	/// <see cref="System.Data.DataSet" /> containing it. If the resulting <see cref="System.Data.DataSet" />
	/// contains no tables, an exception is thrown as specified in the "Exceptions" section above.
	/// </para>
	///
	/// <para>After this, an <see cref="OnAfterEntityUpdate" /> event is raised, sending the following items in the
	/// <see cref="Classes.Bases.AfterEntityUpdateEventArgs" /> object:
	/// <list type="bullet">
	/// <item>The given <c>CentralOfficeEntity</c> to update,</item>
	/// <item>the <c>SqlCommand</c> that was executed,</item>
	/// <item>the value passed in <paramref name="useCheckSum" />, and</item>
	/// <item>the results <c>DataSet</c>.</item>
	/// </list>
	/// </para>
	///
	/// <para>This method then proceeds to reload the passed-in Entity with the values from the returned <c>DataSet</c>. 
	/// If the topmost table is empty, a system exception is thrown as specified in the "Exceptions" section above. If not, row 0 (zero)
	/// is chosen and sent to the Entity's
	/// <see cref="Classes.Entities.CentralOfficeEntity.LoadFromDataRow(System.Data.DataRow, bool)" /> method, with 
	/// <paramref name="useCheckSum" /> set to <c>false</c>. Also, its 
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> property is set to <c>false</c>.
	/// </para>
	///
	/// 
	/// <para><b>Note</b>: there is a version of this method where a checksum is stored previous to updating the Entity and at this 
	/// point compares it with the checksum from the reloaded Entity. This is done to correct discrepancies that may arise even though
	/// <see cref="Classes.Entities.CentralOfficeEntity.EnableDefaults" /> is set to <c>true</c> before executing the UPDATE command.
	/// That method was generated at compile time only for those Entities that are supposed to deal with tables that contain checksum
	/// fields.</para>
	/// 
	/// <para>
	/// Any other exceptions generated at any point in this process are handled by
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	private static void Update(CentralOfficeEntity entityToUpdate, bool useCheckSum)
	{
			try
			{			
				// build command
				System.Data.SqlClient.SqlCommand SqlCmd;
				SqlCmd = new System.Data.SqlClient.SqlCommand();
				SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
				
				SqlCmd.CommandText = "up_CentralOffice_Update";
				
				// parameters
				entityToUpdate.EnableDefaults = true;
				FillCommandParameters(SqlCmd, entityToUpdate);


                // raise before event
				if (OnBeforeEntityUpdate != null)
				{
					Classes.Bases.BeforeEntityUpdateEventArgs args = new Classes.Bases.BeforeEntityUpdateEventArgs();
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					args.EntityToUpdate = entityToUpdate;
					OnBeforeEntityUpdate(null,args);
				}
				
				
				// execute
                SqlCmd.Transaction = ProjectCommon2.Helpers.TransactionManager.Transaction;
				System.Data.DataSet ds;
				ds = ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet(SqlCmd);
				System.Data.DataTable dt;
				if (ds.Tables.Count == 0)
				{
					ProjectCommon2.Exceptions.MissingDataTableException ex = new ProjectCommon2.Exceptions.MissingDataTableException("Results expect at least one member table.");
					ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}
				dt = ds.Tables[0];

                // raise after event
				if (OnAfterEntityUpdate != null)
				{
					Classes.Bases.AfterEntityUpdateEventArgs args = new Classes.Bases.AfterEntityUpdateEventArgs();
					args.SqlCommandToExecute = SqlCmd;
					args.UseCheckSum = useCheckSum;
					args.DataSetFromDataBase = ds;
					args.EntityToUpdate = entityToUpdate;
					OnAfterEntityUpdate(null,args);
				}
				
				// reload
				if (dt.Rows.Count == 0)
				{
					ProjectCommon2.Exceptions.BaseException ex;
					ex = new ProjectCommon2.Exceptions.BaseException(string.Format("Failed on CentralOfficeFactory.Update(): No Data Rows in Data Table."));
                    ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
				}
				
				entityToUpdate.LoadFromDataRow(dt.Rows[0], false);
				entityToUpdate.IsMarkedToDelete = false;

				
			}
			catch (Exception ex)
			{
				ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
			}

	}

    /// <summary>
	/// Removes the database record that corresponds to the given Entity.
	/// </summary>
    /// 
    /// <param name="entityToDelete">Specifies the <c>CentralOfficeEntity</c> whose corresponding record is to be removed.</param>
	/// <param name="obeyIsMarkedToDelete">Specifies if this method should check the given Entity's
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> property before attempting to delete its
	/// corresponding record.</param>
    /// 
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission> 
    /// 
    /// <remarks>
	/// <para>
	/// No work performed here. Calls <see cref="Delete(Classes.Entities.CentralOfficeEntity, bool, bool)" /> with
	/// <paramref name="useCheckSum" /> set to <c>true</c>.
	/// </para>
	/// </remarks>
    [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	private static void Delete(CentralOfficeEntity entityToDelete, bool obeyIsMarkedToDelete)
	{
		Delete(entityToDelete, obeyIsMarkedToDelete,true);
	}

    /// <summary>
	/// Removes the database record that corresponds to the given Entity. Provides the option to disable checksum verification.
	/// </summary>
    /// <param name="entityToDelete">Specifies the <c>CentralOfficeEntity</c> whose corresponding record is to be removed.</param>
	/// <param name="obeyIsMarkedToDelete">Specifies if this method should check that the Entity is marked to be deleted before
	/// attempting to delete its record. If set to <c>false</c>, it will delete the record even if the Entity is not marked to
	/// be deleted.</param>
	/// <param name="useCheckSum">Specifies if a checksum test should be performed to verify the integrity of the data.</param>
    /// 
    /// <permission cref="EnvironmentPermissionAttribute">Specifies that the immediate caller of this method must have full
    /// permission to access environment variables.
	/// </permission>
    /// <exception cref="ProjectCommon2.Exceptions.IsMarkedToDeleteNotTrueException">
	/// Thrown if the given Entity is not marked to be deleted (its <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" />
	/// property is <c>false</c>). Thrown using <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />, which controls
	/// logging and other exception handling activities.
	/// </exception>
    /// 
    /// <remarks>
	/// <para>If <paramref name="obeyIsMarkedToDelete" /> is set to <c>true</c>, this method will check if the given Entity's
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" /> property is <c>true</c> before attempting to delete the 
	/// Entity's record. If the property is <c>false</c>, it will stop and throw an exception as specified in the "Exceptions" section
	/// above. However, if <paramref name="obeyIsMarkedToDelete" /> is <c>false</c>, it will delete the record even if the Entity is not
	/// marked to be deleted.
	/// </para>
	///	<para>This method works by sending parameters to a stored procedure in the database, which in turn executes a DELETE
	/// command with the same parameters. First, a <see cref="System.Data.SqlClient.SqlCommand" /> is built, specifying 
	/// "up_CentralOffice_Delete" as the name of the stored procedure to execute. 
	/// Since <c>CentralOfficeEntities</c> do not have a checksum property, only the Primary Key is sent as a parameter to the
	/// procedure. Note that there is a slightly different version of this method where the checksum is also sent as a parameter, but
	/// that method was generated only for Factories that are supposed to deal with Entities that contain checksum values.</para>
	/// <para>The method then raises an <see cref="OnBeforeEntityDelete" /> event before executing the <c>SqlCommand</c>.
	/// The event argument is an object of type <see cref="Classes.Bases.BeforeEntityDeleteEventArgs" />, which allows this method
	/// to pass the <c>CentralOfficeEntity</c> to be deleted, the <c>SqlCommand</c> to be executed, and the value passed in 
	/// <paramref name="useCheckSum" /> to any object subscribed to the event.
	/// </para>
	///
	/// <para>The <c>SqlCommand</c> is then executed using
	/// <see cref="ProjectCommon2.Helpers.SqlHelper.ExecuteNonQuery(System.Data.SqlClient.SqlCommand)" />.</para>
	///
	/// <para>After this, an <see cref="OnAfterEntityDelete" /> event is raised, sending the following items in the
	/// <see cref="Classes.Bases.AfterEntityDeleteEventArgs" /> object:
	/// <list type="bullet">
	/// <item>The given <c>CentralOfficeEntity</c> to delete,</item>
	/// <item>the <c>SqlCommand</c> that was executed,</item>
	/// <item>the value passed in <paramref name="useCheckSum" />.</item>
	/// </list>
	/// </para>
	///
	/// <para>Finally, to make sure the Entity can not be deleted twice, the Entity's 
	/// <see cref="Classes.Entities.CentralOfficeEntity.IsMarkedToDelete" />, <see cref="Classes.Entities.CentralOfficeEntity.IsNew" />,
	/// and <see cref="Classes.Entities.CentralOfficeEntity.SetManualIsDirty" /> are all set to <c>false</c>.
	/// </para>
	/// <para>
	/// Any other exceptions generated at any point in this process are handled by 
	/// <see cref="ProjectCommon2.Helpers.ExceptionHelper.Throw(System.Exception)" />.
	/// </para>
	/// </remarks>
	[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
	private static void Delete(CentralOfficeEntity entityToDelete, bool obeyIsMarkedToDelete, bool useCheckSum)
	{
			try
			{
				
				if (obeyIsMarkedToDelete && !entityToDelete.IsMarkedToDelete)
				{
					ProjectCommon2.Helpers.ExceptionHelper.Throw(new ProjectCommon2.Exceptions.IsMarkedToDeleteNotTrueException());
				}
				
				// build command
				System.Data.SqlClient.SqlCommand SqlCmd;
				SqlCmd = new System.Data.SqlClient.SqlCommand();
				SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
				SqlCmd.CommandText = "up_CentralOffice_Delete";
				
				// parameters
				SqlCmd.Parameters.AddWithValue("@CentralOfficeId", entityToDelete.CentralOfficeIdObject.Value);

				// fire before event 
				if (OnBeforeEntityDelete != null)
				{
					Classes.Bases.BeforeEntityDeleteEventArgs args = new Classes.Bases.BeforeEntityDeleteEventArgs();
					args.EntityToDelete = entityToDelete;
					args.UseCheckSum = useCheckSum;
					args.SqlCommandToExecute = SqlCmd;
					OnBeforeEntityDelete(null,args);
				}
				
				// execute
                SqlCmd.Transaction = ProjectCommon2.Helpers.TransactionManager.Transaction;
                ProjectCommon2.Helpers.SqlHelper.ExecuteNonQuery(SqlCmd);
				
				// fire after event 
				if (OnAfterEntityDelete != null)
				{
					Classes.Bases.AfterEntityDeleteEventArgs args = new Classes.Bases.AfterEntityDeleteEventArgs();
					args.EntityToDelete = entityToDelete;
					args.UseCheckSum = useCheckSum;
					args.SqlCommandToExecute = SqlCmd;
					OnAfterEntityDelete(null,args);
				}
			}
			
			catch (Exception ex)
			{
				ProjectCommon2.Helpers.ExceptionHelper.Throw(ex);
			}
	}

	#endregion 
	
	#region  " Private Utilities "

    /// <summary>
    /// Inserts the column properties of the given Entity as parameters into the given SQL command object.
    /// </summary>
    /// <param name="sqlCmd">Specifies the <see cref="System.Data.SqlClient.SqlCommand" /> object whose parameters need to be filled.</param>
    /// <param name="entityToUse">Specifies the <c>CentralOfficeEntity</c> to extract parameter values from.</param>
	/// 
	/// <remarks>
	/// <para>Goes through every column property in the given Entity (the list of columns is from the source table specified at build time)
	/// and <see cref="System.Data.SqlClient.SqlParameterCollection.Add(System.Data.SqlClient.SqlParameter)" />s a
	/// <see cref="System.Data.SqlClient.SqlParameter" /> to the passed-in <c>SqlCommand</c>. The <see cref="System.Data.SqlClient.SqlParameter.SqlDbType" />, 
	/// <see cref="System.Data.SqlClient.SqlParameter.ParameterName" />, <see cref="System.Data.SqlClient.SqlParameter.Direction" />, and 
	/// of course, <see cref="System.Data.SqlClient.SqlParameter.Value" /> are specified for every parameter.
	/// </para>
	/// <para>Note: The code that determines what values are assigned to <c>SqlDbType</c>, <c>ParameterName</c>, and <c>Value</c> was generated
	/// using the appropriate column from the source table specified at build time.
	/// </para>
	/// </remarks>
	private static void FillCommandParameters(System.Data.SqlClient.SqlCommand sqlCmd,  CentralOfficeEntity entityToUse)
	{
		System.Data.SqlClient.SqlParameter SqlParam;
		// CentralOfficeId
		if (entityToUse.CentralOfficeId != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.Int;
			SqlParam.ParameterName = "@CentralOfficeId";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.CentralOfficeId;
			sqlCmd.Parameters.Add(SqlParam);
		}
		// Name
		if (entityToUse.Name != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.NVarChar;
			SqlParam.ParameterName = "@Name";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.Name;
			sqlCmd.Parameters.Add(SqlParam);
		}
		// Latitude
		if (entityToUse.Latitude != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.Float;
			SqlParam.ParameterName = "@Latitude";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.Latitude;
			sqlCmd.Parameters.Add(SqlParam);
		}
		// Longitude
		if (entityToUse.Longitude != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.Float;
			SqlParam.ParameterName = "@Longitude";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.Longitude;
			sqlCmd.Parameters.Add(SqlParam);
		}
		// Address
		if (entityToUse.Address != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.NVarChar;
			SqlParam.ParameterName = "@Address";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.Address;
			sqlCmd.Parameters.Add(SqlParam);
		}
		// UtilityFk
		if (entityToUse.UtilityFk != null)
		{
			SqlParam = new System.Data.SqlClient.SqlParameter();
			SqlParam.SqlDbType = System.Data.SqlDbType.Int;
			SqlParam.ParameterName = "@UtilityFk";
			SqlParam.Direction = System.Data.ParameterDirection.Input;
			SqlParam.Value = entityToUse.UtilityFk;
			sqlCmd.Parameters.Add(SqlParam);
		}
	}
	
	#endregion
			
	#region " Events "
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to retrieve a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeGetEntityEventArgs> OnBeforeGetEntity;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to retrieve a <c>CentralOfficeEntity</c> collection.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeGetEntityCollectionEventArgs> OnBeforeGetEntityCollection;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to INSERT a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeEntityInsertEventArgs> OnBeforeEntityInsert;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to UPDATE a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeEntityUpdateEventArgs> OnBeforeEntityUpdate;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to DELETE a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeEntityDeleteEventArgs> OnBeforeEntityDelete;
		/// <summary>
        /// Notifies its assigned delegate that <c>CentralOfficeFactory</c> succesfully retrieved a(n) <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.AfterGetEntityEventArgs> OnAfterGetEntity;
		/// <summary>
        /// Notifies its assigned delegate that <c>CentralOfficeFactory</c> succesfully retrieved a(n) <c>CentralOfficeEntity </c> collection.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.AfterGetEntityCollectionEventArgs> OnAfterGetEntityCollection;
		/// <summary>
        /// Notifies its assigned delegate that <c>CentralOfficeFactory</c> succesfully INSERTed a(n) <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.AfterEntityInsertEventArgs> OnAfterEntityInsert;
		/// <summary>
        /// Notifies its assigned delegate that <c>CentralOfficeFactory</c> succesfully UPDATEd a(n) <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.AfterEntityUpdateEventArgs> OnAfterEntityUpdate;
		/// <summary>
        /// Notifies its assigned delegate that <c>CentralOfficeFactory</c> succesfully DELETEd a(n) <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.AfterEntityDeleteEventArgs> OnAfterEntityDelete;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to save a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeSaveEntityBeginEventArgs> OnBeforeSaveEntityBegin;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to commit a save operation for a <c>CentralOfficeEntity</c>.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeSaveEntityCommitEventArgs> OnBeforeSaveEntityCommit;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to save a <c>CentralOfficeEntity</c> collection.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeSaveCollectionBeginEventArgs> OnBeforeSaveCollectionBegin;
		/// <summary>
        /// Notifies its assigned delegate when <c>CentralOfficeFactory</c> is about to commit a save operation for a <c>CentralOfficeEntity</c> collection.
        /// </summary>
        public static event System.EventHandler<Classes.Bases.BeforeSaveCollectionCommitEventArgs> OnBeforeSaveCollectionCommit;
	
    #endregion
			
	}
}
